import axios from 'axios'
import { getToken } from '@/utils/auth'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// 1. 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '/api',
  timeout: 15000
})

// 2. 请求拦截器
service.interceptors.request.use(
  config => {
    // 排除注册/登录接口
    if (!['/register', '/login'].some(path => config.url.includes(path))) {
      const token = getToken()
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
    }
    return config
  },
  error => Promise.reject(error)
)

// 3. 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response?.status === 401 && !error.config.url.includes('/register')) {
      const authStore = useAuthStore()
      authStore.logout()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

// 4. 导出实例
export default service